package com.linkage.jz.bankruptcy.activity.Project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.ProTaskDetail;
import com.linkage.jz.bankruptcy.bean.TaskAtta;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.datepicker.CustomDatePicker;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;
import com.linkage.seapeak.pojo.UploadImage;
import com.linkage.seapeak.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * 创建任务
 */
public class CreateProTaskActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = CreateProTaskActivity.class.getSimpleName();
    public static final String KEY_ACTION = "action";
    public static final String KEY_TASK = "task";

    private String mProjectID;
    private ProTaskDetail mProTaskDetail;

    private long mTime = -1;

    private RecyclerView mImgRecyclerView;
    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter adapter;

    private EditText et_task_name, et_task_desc;
    private TextView tv_task_missonexer, tv_task_time;
    private CustomDatePicker mTimerPicker;

    @Override
    public void initData() {
    }

    @Override
    public void setListener() {
    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }

    private CommonPromptDialog mPromptDialog;
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this,CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", new OnClickListener() {
            @Override
            public void onClick(View view) {
                CreateProTaskActivity.super.onBackPressed();
            }
        });
        mPromptDialog.setNegativeClickListener("否", new OnClickListener() {
            @Override
            public void onClick(View view) {
                mPromptDialog.dismiss();
            }
        });
        mPromptDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_pro_task);
        super.onCreate(savedInstanceState);

        if (TextUtils.equals(getIntent().getStringExtra(KEY_ACTION), "edit")) {
            mProTaskDetail = (ProTaskDetail) getIntent().getSerializableExtra(KEY_TASK);
            mProjectID = mProTaskDetail.getBankruptcyProjectId();
        } else {
            mProjectID = getIntent().getStringExtra(KEY_PROJECTID);
        }
        if (mProTaskDetail != null) {
            titlebar_title.setText("编辑任务");
        } else {
            titlebar_title.setText("新建任务");
        }
        titlebar_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        initViews();
        titlebar_menu_text.setOnClickListener(this);
    }

    public void initViews() {
        titlebar_menu_text.setVisibility(View.VISIBLE);
        et_task_name = findViewById(R.id.et_task_name);
        et_task_desc = findViewById(R.id.et_task_desc);
        tv_task_time = findViewById(R.id.tv_task_time);
        tv_task_missonexer = findViewById(R.id.tv_task_missonexer);

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView.setLayoutManager(manager);
        adapter = new GridImagesAdapter(this, TYPE_EDIT);
        adapter.setList(mImgList);
        mImgRecyclerView.setAdapter(adapter);

        if (mProTaskDetail != null) {
            et_task_name.setText(mProTaskDetail.getTaskName());
            et_task_desc.setText(mProTaskDetail.getTaskContent());
            tv_task_missonexer.setText(mProTaskDetail.getExecutor().getUsername());
            seluserId =  mProTaskDetail.getMemberId();
            selsysuserId = mProTaskDetail.getSysUserId();
            mTime = mProTaskDetail.getDeadlineTime();
            tv_task_time.setText(DateFormatUtils.long2Str(mProTaskDetail.getDeadlineTime(), true));
            for (int i = 0; i < mProTaskDetail.getTaskAtta().size(); i++) {
                TaskAtta atta = mProTaskDetail.getTaskAtta().get(i);
                JSONObject obj = new JSONObject();
                try {
                    obj.putOpt("filename", atta.getAttachmentName());
                    obj.putOpt("filepath", atta.getAttachmentDownloadAddress());
                    obj.putOpt("filesize", atta.getAttachmentSize());
                    obj.putOpt("loadUrl", atta.getAttachmentWatermarkAddress());
                    mImgList.add(new Gson().fromJson(obj.toString(), UploadImage.class));
                    BaseCreateActivity.sorFiles(mImgList,true);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:

                break;
            case R.id.ll_phonelogin:
                PhoneLoginActivity.start(this);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.titlebar_menu_text:
                saveData();
                break;
            case R.id.tv_task_time:
                chooseTime();
                break;
            case R.id.tv_task_missonexer:
                Intent intent = new Intent(CreateProTaskActivity.this, ManagerSelListActivity.class);
                intent.putExtra("mProjectID", mProjectID);
                intent.putExtra("form","id");
                startActivityForResult(intent, REQUEST_SEL_JION_ACTIVITY);
                break;

            default:
                break;
        }


    }

    public final int REQUEST_SEL_LOOK_ACTIVITY = 10001;
    public final int REQUEST_SEL_JION_ACTIVITY = 10002;
    public String seluserName = "";
    public String seluserId = "";
    public String selsysuserId = "";
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {

            case REQUEST_SEL_JION_ACTIVITY:
                if (resultCode == RESULT_OK) {
                    if (intent != null) {
                        seluserName = intent.getStringExtra("seluserName");
                        seluserId = intent.getStringExtra("seluserId");
                        selsysuserId = intent.getStringExtra("selsysuserId");
                        tv_task_missonexer.setText(seluserName);
                    }
                }
                break;

        }
    }


    private void chooseTime() {
        String beginTime = "2010-01-01 00:00";
        String endTime = "2099-12-31 00:00";
        mTimerPicker = new CustomDatePicker(CreateProTaskActivity.this, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp) {
                //返回值处理
                mTime = timestamp;
                Date d = new Date();
                d.setTime(timestamp);
                tv_task_time.setText(DateFormatUtils.long2Str(d.getTime(), true));
            }
        }, beginTime, endTime);
        mTimerPicker.setCancelable(true);
        mTimerPicker.setCanShowPreciseTime(true); //如果这里用true，上面的开始和结束时间要对应
        mTimerPicker.setScrollLoop(true);
        mTimerPicker.setCanShowAnim(true); //建议不要用
        if (mTime < 0) {
            mTime = System.currentTimeMillis();
        }
        mTimerPicker.show(DateFormatUtils.long2Str(mTime, true));
    }


    public void saveData() {
        String taskName = et_task_name.getText().toString();
        String taskDesc = et_task_desc.getText().toString();
        if (TextUtils.isEmpty(taskName)) {
//            ToastUtil.showShort("名称不能为空");
//            ToastUtil.showShort("任务名称不能为空");
            showToast("任务名称不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (TextUtils.isEmpty(taskDesc)) {
//            ToastUtil.showShort("内容不能为空");
//            ToastUtil.showShort("任务内容不能为空");
            showToast("任务内容不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        if (TextUtils.isEmpty(seluserId)) {
//            ToastUtil.showShort("请选择执行人");
//            ToastUtil.showShort("请选择执行人");
            showToast("请选择执行人", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        if (mTime < 0) {
//            ToastUtil.showShort("请选择截止时间");
//            ToastUtil.showShort("请选择截止时间");
            showToast("请选择截止时间", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();

        JSONArray fileArr = new JSONArray();
        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(mImgList.get(i).getFilename())) {
                    obj.putOpt("filename", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("filename", mImgList.get(i).getFilename());
                }
                obj.putOpt("filepath", mImgList.get(i).getFilepath());
                obj.putOpt("filesize", mImgList.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        Observable<JsonObject> observable;
        if (mProTaskDetail != null) {
            observable = Network
                    .getAPIService()
                    .editTask(getUserToken(), mProTaskDetail.getId(), mProTaskDetail.getBankruptcyProjectId(),
                            taskName, taskDesc, selsysuserId,seluserId, mTime, fileArr.toString());
        } else {
            observable = Network
                    .getAPIService()
                    .sendTask(getUserToken(), mProjectID, taskName, taskDesc,selsysuserId, seluserId, mTime, fileArr.toString());
        }

        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {

                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TASK);
                        EventBus.getDefault().post(event);
//                        ToastUtil.showShort("提交成功");
                        showToast("提交成功", ToastUtil.TOAST_TYPE.SUCCESS);

                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }
}

